
module.exports =  {
  setToken(token){
    this.$store.commit('user/updateToken', token);
  },
  replacePage(url=''){
    let pages = getCurrentPages(); // 获取栈实例
    if(!pages.length)
      return;
      // /pages/login/index
    let currentRoute = pages[pages.length - 1].route; // 获取当前页面路由
     
    // 当前路由一致不需要重定向
    if(url.indexOf(currentRoute) > -1){
      console.log('路由一致,不需要重定向')
      return;
    }
    
    uni.reLaunch({
      url
    })
  },
  // 防暴力点击
  checkTouch(){
    if(this.loading)
      return false;
    this.loading = true;
    setTimeout(()=>{this.loading = false},1000);
    return true
  },
  // 获取用户信息
  async getInfo(){
    let info = await this.$apis.user.info();
    this.$store.commit('user/updateInfo', info.data);
  },
  // 查询打卡详情
  async clockCheck(){
    let res = await this.$apis.user.clockCheck();
    this.$store.commit('user/updateClocks', res.data);
  },
  // 查询用户状态
  async checkUser(refreshToken=true){
    
    // return this.replacePage('/pages/mapHome/scan')
    // return this.replacePage('/pages/mapHome/index')
    // return this.replacePage('/pages/punckClock/index');
    // return this.replacePage('/pages/login/index');
    // return this.replacePage('/pages/home/index');
    // return this.replacePage('/pages/braceletQr/index');
    // return this.replacePage('/pages/punckClock/photo');
    // return this.replacePage('/pages/writeOff/index');
    
    // 不需要做检测的接口
    const excludedPaths = [
      '/pages/punckClock/photo',
      '/pages/writeOff/index',
      '/pages/rank/rank',
      'pages/scanResult/scanResult'
    ];
    
    if (excludedPaths.some(path => location.href.includes(path))) {
      return;
    }
     
    if(this.profile.uuid){
      
      // 刷新token
      if(refreshToken){
        let tokenRes = await this.$apis.user.updateToken({uuid:this.profile.uuid}).catch(e=>{
          // 报错重新注册
          return uni.$emit('login')
        });
        this.setToken(tokenRes.data.access_token);
      }
     
      // 更新最新数据
      await this.getInfo();
      await this.clockCheck();
      
      // 判断是否已经绑定rfid
      if(!this.profile.is_bind){
        return this.replacePage('/pages/braceletQr/index');
      }
      
     
      // 判断是否已经生成虚拟头像
      if(!this.profile.has_avatar){
        return this.replacePage('/pages/home/index');
      }
      // 未完成虚拟头像打卡
      if(!this.clocks.length || !this.clocks.includes('digital_identity')){
        return this.replacePage('/pages/punckClock/index');
      }
    
      // 已经有虚拟头像并打卡过了直接到地图页
      if(this.clocks.length && this.clocks.includes('digital_identity')){
        return this.replacePage('/pages/mapHome/index');
      }
    }else{
      return this.replacePage('/pages/login/index');
    }

  }
}